import { _decorator, Component, find, Node, Rect, tween, v3, Vec3 } from 'cc';
import { Emitter } from '../../../FrameWork3.8.6/FrameWork/Common/Emitter';
import { ModuleBase } from '../../../FrameWork3.8.6/FrameWork/Module/ModuleBase';
import { ModuleMgr } from '../../../FrameWork3.8.6/FrameWork/Module/ModuleMgr';
import { PlayerLayer } from '../ModuleLayer/PlayerLayer';
const { ccclass, property } = _decorator;

@ccclass('FollowCamera')
export class FollowCamera extends Component {
    //跟随的目标节点
    private _targetNode:Node=null;

    //是否开始跟随
    private _isFollow:boolean=false;

    //相机需要的位置
    private _targetPos:Vec3=new Vec3();

    start() {
        Emitter.instance.on("FollowCamera",this.attachPlayer,this);
        Emitter.instance.on("RemoveCamera",this.removeCamera,this)
    }

    //相机跟随玩家的方法
    attachPlayer(){
        this._targetNode=ModuleMgr.instance.getModule<PlayerLayer>("_PlayerLayer").player.node;
        this._isFollow=true;
    }
        

    //解除相机跟随
    removeCamera(){
        //先设置父亲
        this.node.parent=find("Canvas");
        this.node.setPosition(v3(0,0));
        this._isFollow=false;
    }
    update(deltaTime: number) {
        if(!this._isFollow){
            return;
        }
        this._targetPos.set(this._targetNode.worldPosition.x,this.node.worldPosition.y,this.node.worldPosition.z);
        //限制左右边界
        this._targetPos.x=Math.max(960,Math.min(2880,this._targetPos.x));

        //真正的跟随逻辑
        tween(this.node)
        .to(0.1,{worldPosition:this._targetPos},{easing:"smooth"})
        .start();
        

    }
}


